<?php

namespace App\Models;

use Illuminate\Foundation\Auth\User as Authenticatable;

/**
 * Class User
 * @package App\Models
 * @author zjw
 * 用户模型
 */
class User extends Authenticatable
{
    const AUTOMATIC_ORDERING = 1;           // 自动订单
    const NOT_AUTOMATIC_ORDERING = 0;       // 手动订单

    const ACTIVE = 1;                       //启用
    const DISABLED = 0;                     //禁用

    protected $fillable = [
        'name', 'phone', 'avatar', 'balance', 'sex', 'user_no', 'school_id', 'role_id', 'morning_rule', 'lunch_rule', 'dinner_rule', 'source_from'
    ];

    protected $hidden = [
        'session_key', 'auth_token', 'unionid', 'mp_openid', 'login_code', 'official_openid'
    ];

    protected $casts = [
        'balance' => 'float',
        'freeze_balance' => 'float'
    ];

    /**
     * @param $query
     * @param $roleId
     */
    public function scopeRoleIs($query, $roleId)
    {
        $query->when($roleId, function ($query) use ($roleId) {
            $query->where('role_id', $roleId);
        });
    }

    /**
     * @param $query
     * @param $schoolId
     */
    public function scopeSchoolIs($query, $schoolId)
    {
        $query->when($schoolId, function ($query) use ($schoolId) {
            $query->where('school_id', $schoolId);
        });
    }

    public function scopeFrom($query, $from)
    {
        $query->when($from, function ($query) use ($from) {
            $query->where('source_from', $from);
        });
    }

    public function scopeNameLike($query, $name)
    {
        $query->when($name, function ($query) use ($name) {
            $query->where('name', 'like', $name . '%');
        });
    }

    public function scopePhoneLike($query, $phone)
    {
        $query->when($phone, function ($query) use ($phone) {
            $query->where('phone', 'like', $phone . '%');
        });
    }

    /**
     * @return \Illuminate\Database\Eloquent\Relations\BelongsTo
     */
    public function role()
    {
        return $this->belongsTo(UserRole::class, 'role_id');
    }

    /**
     * @return \Illuminate\Database\Eloquent\Relations\BelongsTo
     */
    public function school()
    {
        return $this->belongsTo(School::class, 'school_id');
    }

    /**
     * @return \Illuminate\Database\Eloquent\Relations\HasMany
     */
    public function bookOrderStatistics()
    {
        $request = \request();
        $date = $request->input('date', date('Y-m'));
        $nextMonth = date('Y-m', strtotime('+1 months', strtotime($date)));
        return $this->hasMany(BookOrder::class)
            ->whereHas('rule', function ($query) use ($date, $nextMonth) {
                $query->where('eat_date', '>', $date)->where('eat_date', '<', $nextMonth);
            })->where('school_id', \Auth::user()->school_id)
            ->where('status', '<>', BookOrder::ORDER_STATUS_CANCELED);
    }

    /**
     * @return string
     * 来源语义化
     */
    public function getSourceFormatAttribute()
    {
        switch ($this->source_from) {
            case("backend"):
                return "后台添加";
                break;
            case("school"):
                return "智慧校园同步";
                break;
            case("import"):
                return "后台导入";
                break;
            default:
                return "";
        }
    }

    /**
     * @param BookRule $bookRule
     * @param null $childrenId
     * @return mixed
     * 判断是否已定
     */
    public function isBookedByRule(BookRule $bookRule, $childrenId = null)
    {
        if (is_null($childrenId)) {
            $where = [
                ['book_rule_id', $bookRule->id],
                ['status', "<>", 40],
                ['user_id', $this->id],
                ['type', BookOrder::TYPE_NORMAL]
            ];
        } else {
            $where = [
                ['book_rule_id', $bookRule->id],
                ['status', "<>", 40],
                ['user_id', $this->id],
                ['children_id', $childrenId],
                ['type', BookOrder::TYPE_CHILDREN]
            ];
        }
        return BookOrder::where($where)->exists();
    }

    /**
     * @param BookRule $bookRule
     * @param null $childrenId
     * @return bool
     * 判断是否能够订餐
     */
    public function canBookByRule(BookRule $bookRule, $childrenId = null)
    {
        if (is_null($childrenId)) {
            // 角色是否能订
            if ($this->role) {
                switch ($bookRule->eat_type) {
                    case BookRule::EAT_TYPE_BREAKFAST:
                        if (!$this->role->canBookBreakfast()) {
                            return false;
                        }
                        break;
                    case BookRule::EAT_TYPE_LUNCH:
                        if (!$this->role->canBookLunch()) {
                            return false;
                        }
                        break;
                    case BookRule::EAT_TYPE_DINNER:
                        if (!$this->role->canBookDinner()) {
                            return false;
                        }
                }
                return !$this->isBookedByRule($bookRule);
            } else {
                return false;
            }
        } else {
            return !$this->isBookedByRule($bookRule, $childrenId);
        }
    }


    /**
     * @return mixed
     */
    public function initOrders()
    {
        return $this->hasMany(BookOrder::class)->isInit();
    }
}
